﻿using Aliyun.OSS;
using System;
using System.IO;
using System.Net;
using DBEntitie;
using FrameWork;

namespace FrameWork
{
   public sealed class OssHelp
   {
        private static readonly string Endpoint = ConfigurationManager.AppSettings("OSS_Endpoint");
        private static readonly string Bucket = ConfigurationManager.AppSettings("OSS_bucket");
        private static readonly string AccessKeyId = ConfigurationManager.AppSettings("OSS_AccessKeyID");
        private static readonly string AccessKeySecret = ConfigurationManager.AppSettings("OSS_AccessKeySecret");
        private static OssClient _instance;
        private static readonly object Lockobj = new object();
        private static OssClient Instance
        {
            get
            {
                if (_instance != null) return _instance;

                lock (Lockobj)
                {
                    _instance = new OssClient(Endpoint, AccessKeyId, AccessKeySecret);
                }

                return _instance;
            }
        }
       public static bool PutObject(string filename, Stream stream, out byte[] bytes, out string osshref)
       {
            bytes = PublicTool.StreamToBytes(stream);
            return PutObject(filename, bytes, out osshref);
        }

       public static bool PutObject(string filename, byte[] binaryData, out string osshref)
       {
            osshref = "";
            try
            {
                var requestContent = new MemoryStream(binaryData);
                var resault = Instance.PutObject(Bucket, filename, requestContent);
                osshref = $"http://{Bucket}.{Endpoint}/{filename}";
                return resault.HttpStatusCode.Equals(HttpStatusCode.OK);
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
